﻿namespace LiteBlog.Controllers
{
    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Security;
    using LiteBlog.Common;
    using LiteBlog.Components;
    using LiteBlog.Common.Entities;
    using LiteBlog.Components.Contracts;
    using LiteBlog.Components.Enums;
    using System.Web.Script.Serialization;
    using LiteBlog.Common.Enums;
    using LiteBlog.Controllers.Filters;
    using LiteBlog.Models;
    using LiteBlog.Controllers.Helpers;
    using LiteBlog.Common.Components;
    using LiteBlog.Controllers.Contracts;

    public class AdminController : BaseController, IAdminController
    {
        private IPageComp _pageComp;
        public IPageComp PageComponent
        {
            get
            {
                return _pageComp;
            }
        }

        private IAuthorComp _authorComp;
        public IAuthorComp AuthorComponent
        {
            get
            {
                return _authorComp;
            }
        }
        public IAuthenticationHelper AuthenticationHelper
        {
            get
            {
                return _auth;
            }
        }

        public AdminController(IAuthenticationHelper auth, IPageComp pageComp, IAuthorComp authorComp, ISettingsComp settingsComp, ICacheComp cacheComp)
            : base(settingsComp, cacheComp)
        {
            _auth = auth;
            _pageComp = pageComp;
            _authorComp = authorComp;
        }

        public ActionResult Menu()
        {
            return PartialView("MenuControl");
        }

        public ActionResult Title()
        {
            var model = PageComponent.GetPagesInHeaderMenu();
            var settings = SettingsComponent.Load();
            ViewBag.Title = settings.Name;
            ViewBag.UseImage = settings.UseImage;
            ViewBag.ImageUrl = settings.ImageUrl;
            this.ViewData["IsAuthenticated"] = this.User.Identity.IsAuthenticated;
            this.ViewData["UserName"] = this.User.Identity.IsAuthenticated ? this.User.Identity.Name : string.Empty;
            return this.PartialView("TitleControl", model);
        }

        [HttpGet]
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        [AjaxExceptionFilter]
        [ValidateFilter]
        [Authorize]
        [Resolve("AuthorComponent")]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            var result = AuthorComponent.ValidateUser(model.Name, model.Password);
            if (result == MethodResult.LoginSuccess)
                result = AuthorComponent.ChangePassword(model.Name, model.Password, model.NewPassword);
            var resultModel = GetResultModel(result, model.Name);
            return Json(resultModel);
        }

        [PageExceptionFilter]
        public ActionResult Index()
        {
            if (AuthorComponent.Get().Count() == 0)
            {
                var author = new Author();
                author.ID = "admin";
                author.Name = "admin";
                author.Email = "admin@liteblog.com";
                author.IsPrimary = true;
                author.Enabled = true;
                AuthorComponent.Create(author);
            }

            // Use FormsAuthentication.DefaultUrl only from home page
            // Use UrlReferer otherwise
            var defaultUrl = AuthenticationHelper.DefaultUrl;
            var referrer = HttpContext.Request.UrlReferrer;
            if (referrer != null && (HttpContext.Request.Url.Authority == referrer.Authority))
            {
                var path = referrer.AbsolutePath;
                var appPath = HttpContext.Request.ApplicationPath;

                if (appPath.Equals("/") && !path.Equals("/"))
                    defaultUrl = path;
                else if (appPath.Length > 1 && !path.Equals(appPath + "/"))
                    defaultUrl = path;
            }

            ViewBag.ReturnUrl = string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]) ? defaultUrl : Request.QueryString["ReturnUrl"];
            return this.View();
        }

        [HttpPost]
        [ValidateFilter]
        [AjaxExceptionFilter]
        public ActionResult Login(LoginModel model)
        {
            var result = AuthorComponent.ValidateUser(model.Name, model.Password);
            if (result == MethodResult.LoginSuccess)
            {
                AuthenticationHelper.SignIn(model.Name);
            }
            var resultModel = GetResultModel(result, null);
            return Json(resultModel);
        }

        [Authorize]
        public ActionResult Logout()
        {
            AuthenticationHelper.SignOut();
            return this.RedirectToAction("Index");
        }

        public void ResolveComponents()
        {
            
        }

        private IAuthenticationHelper _auth;
    }
}